import path from 'node:path';
import fs from 'node:fs';
import select from '@inquirer/select';
import input from '@inquirer/input';
import chalk from 'chalk';

const log = console.log;

const optionsConfig = [
  {
    name: 'page',
    value: 'page'
  },
  {
    name: 'component',
    value: 'component'
  }
];

const pathConfig = {
  page: path.join(__dirname, '../miniprogram/pages'),
  component: path.join(__dirname, '../miniprogram/components'),
  lib: path.join(__dirname, './lib'),
  appJson: path.join(__dirname, '../miniprogram/app.json')
};

const getRootClassName = (type: 'page' | 'component', name: string) => {
  return `${type === 'page' ? 'p' : 'c'}-${name}`;
};

async function generator() {
  const type = (await select({
    message: 'Generation options',
    choices: optionsConfig
  })) as 'component' | 'page';

  const name = await input({
    message: `Input ${type} name`
  });

  if (!name) return void log(chalk.red('Please input name!'));

  // 最终文件夹路径
  const folderPath = path.join(pathConfig[type], name);

  // 生成文件夹
  try {
    fs.accessSync(folderPath);
    log(chalk.yellow('Folder already existed!'));
  } catch (e) {
    fs.mkdirSync(folderPath, {
      recursive: true
    });
  }

  // 将lib文件模板复制到generatedPath
  const libPath = pathConfig['lib'];
  const templateFiles = await fs.readdirSync(libPath, {
    encoding: 'utf-8'
  });
  for (const filename of templateFiles) {
    if (type === 'page' && filename.indexOf('c-') > -1) continue;
    if (type === 'component' && filename.indexOf('p-') > -1) continue;
    const suffix = path.extname(filename);
    fs.copyFileSync(path.join(libPath, filename), path.join(folderPath, `${name}${suffix}`));
  }

  // 处理模板文件中占位符
  const paths = [path.join(folderPath, `${name}.wxml`), path.join(folderPath, `${name}.scss`)];
  for (const path of paths) {
    let txt = fs.readFileSync(path, { encoding: 'utf-8' });
    txt = txt.replace('_TCSS', getRootClassName(type, name));
    fs.writeFileSync(path, txt);
  }

  // 如果是页面，在app.json注册页面
  if (type === 'page') {
    const contentStr = JSON.parse(
      fs.readFileSync(pathConfig.appJson, {
        encoding: 'utf-8'
      })
    );
    contentStr.pages.unshift(`pages/${name}/${name}`);
    fs.writeFileSync(pathConfig.appJson, JSON.stringify(contentStr, null, 2));
  }

  log(chalk.green('done'));
}

generator();
